//    Travel US - For users of travel.usairways.com
//    intended for US Airways employees and their dependents
//    This app will help you track your flights and display
//    Availability, flight status and other non-rev info
//    Copyright (C) 2014  Renats Stozkovs
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.bc004346.travelus.Activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bc004346.travelus.AsyncTasks.SearchFlightsTaskFragment;
import com.bc004346.travelus.Fragment.NavigationDrawerFragment;
import com.bc004346.travelus.Model.Domain.Flight;
import com.bc004346.travelus.R;
import com.google.analytics.tracking.android.EasyTracker;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import static com.bc004346.travelus.Utility.DAY;
import static com.bc004346.travelus.Utility.SHORT_DATE;
import static com.bc004346.travelus.Utility.dateInputFilter;
import static com.bc004346.travelus.Utility.getTravelUS;
import static com.bc004346.travelus.Utility.log;

/**
 * Created by Renats on 3/9/14.
 * Book Travel
 */
public class BookTravelActivity extends Activity
        implements SearchFlightsTaskFragment.TaskCallbacks {

    //<editor-fold desc="Members">

    public static final String SEARCH_TASK_TAG = "searchTask";
    private NavigationDrawerFragment mNavigationDrawer;
    private EditText origin;
    private EditText destination;
    private EditText departureDate;
    private EditText returnDate;
    private TextView textViewMessage;
    private RadioButton oneWay;
    private Button buttonSearch;
    private FragmentManager mFragmentManager;

    //</editor-fold>
    //<editor-fold desc="Properties">

    public String getOrigin() {
        Editable x = origin.getText();
        return x == null ? "" : x.toString();
    }

    public String getDestination() {
        Editable x = destination.getText();
        return x == null ? "" : x.toString();
    }

    public Date getDeparture() {
        Editable x = departureDate.getText();
        Date date = null;
        try {
            DateFormat df = SHORT_DATE;
            df.setLenient(false);
            date = df.parse(x != null ? x.toString() : null);
        } catch (ParseException e) {
            log(e.toString());
        }
        return date;
    }

    public Date getReturn() {
        Editable x = returnDate.getText();
        Date date = null;
        try {
            DateFormat df = SHORT_DATE;
            df.setLenient(false);
            date = df.parse(x != null ? x.toString() : null);
        } catch (ParseException e) {
            log(e.toString());
        }
        return date;
    }

    public boolean isOneWay() {
        return oneWay.isChecked();
    }

    //</editor-fold>
    //<editor-fold desc="Overrides">

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_travel);

        setupUI();
    }

    @Override
    protected void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mNavigationDrawer.syncState();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        mNavigationDrawer.handleOnPrepareOptionsMenu(menu);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        mNavigationDrawer.syncState();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        mNavigationDrawer.handleOnOptionsItemSelected(item);
        return super.onOptionsItemSelected(item);
    }

    //</editor-fold>
    //<editor-fold desc="Private Methods">

    private void setupUI() {
        try {
            mNavigationDrawer = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fullscreenDrawer);
            if (mNavigationDrawer != null)
                mNavigationDrawer.init();

            origin = (EditText) findViewById(R.id.bookTravel_editTextOrigin);
            destination = (EditText) findViewById(R.id.bookTravel_editTextDestination);
            departureDate = (EditText) findViewById(R.id.bookTravel_editTextDeparture);
            returnDate = (EditText) findViewById(R.id.bookTravel_editTextReturn);
            RadioGroup radioGroup = (RadioGroup) findViewById(R.id.bookTravel_radioButtonGroup);
            oneWay = (RadioButton) findViewById(R.id.bookTravel_radioButtonOneWay);
            buttonSearch = (Button) findViewById(R.id.bookTravel_buttonSearch);
            textViewMessage = (TextView) findViewById(R.id.bookTravel_textViewMessage);
            mFragmentManager = getFragmentManager();

            //TODO remove after testing
            origin.setText("PHX");
            destination.setText("CLT");
            oneWay.setChecked(true);
            departureDate.setText("03/25/14");

            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    returnDate.setVisibility(oneWay.isChecked() ? View.INVISIBLE : View.VISIBLE);
                }
            });
            buttonSearch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isInputValid()) searchFlights();
                }
            });

            departureDate.setFilters(new InputFilter[]{dateInputFilter});
            returnDate.setFilters(new InputFilter[]{dateInputFilter});
        } catch (Exception e) {
            log(e, this);
        }
    }

    private boolean isInputValid() {

        StringBuilder message = new StringBuilder();

        try {
            if (getOrigin().length() != 3)
                message.append("Origin should be 3 characters long\n\r");

            if (getDestination().length() != 3)
                message.append("Destination should be 3 characters long\n\r");

            if (getDeparture() == null)
                message.append("Unable to parse Departure Date\n\r");
            else if (getDeparture().getTime() < new Date().getTime() - DAY)
                message.append("Departure Date cannot be in the past\n\r");

            if (!isOneWay() && getReturn() == null)
                message.append("Unable to parse Return Date\n\r");
            else if (!isOneWay() && getReturn().getTime() < new Date().getTime() - DAY)
                message.append("Return Date cannot be in the past\n\r");

            if (!isOneWay() && getDeparture().getTime() > getReturn().getTime())
                message.append("Departure Date cannot be greater than Return Date\n\r");

            if (message.length() == 0)
                return true;

            textViewMessage.setText(message.toString());
        } catch (Exception e) {
            log(e, this);
        }
        return false;
    }

    private void searchFlights() {
        try {
            buttonSearch.setText(getString(R.string.bookTravel_ButtonSearchTextAlt));
            buttonSearch.setEnabled(false);
            SearchFlightsTaskFragment fragment =
                    (SearchFlightsTaskFragment) mFragmentManager.findFragmentByTag(SEARCH_TASK_TAG);
            if (fragment == null) {
                fragment = new SearchFlightsTaskFragment(getTravelUS(),
                        getOrigin(),
                        getDestination(),
                        getDeparture(),
                        getReturn(),
                        isOneWay());
                mFragmentManager.beginTransaction().add(fragment, SEARCH_TASK_TAG).commitAllowingStateLoss();
            }
        } catch (Exception e) {
            log(e, this);
        }
    }

    private void removeSearchFragment() {
        try {
            SearchFlightsTaskFragment fragment =
                    (SearchFlightsTaskFragment) getFragmentManager().findFragmentByTag(SEARCH_TASK_TAG);
            if (fragment != null)
                mFragmentManager.beginTransaction().remove(fragment).commitAllowingStateLoss();
        } catch (Exception e) {
            log(e, this);
        }
    }

    //</editor-fold>
    //<editor-fold desc="Callbacks">

    @Override
    public void onSearchPostExecute(List<Flight> flights, Exception e) {
        try {
            buttonSearch.setText(getString(R.string.bookTravel_ButtonSearchText));
            buttonSearch.setEnabled(true);
            removeSearchFragment();

            if (e != null) {
                textViewMessage.setText(e.getMessage());
                log(e, this);
                return;
            }

            if (flights == null) {
                textViewMessage.setText(getString(R.string.dashboardStatus_NoFlightsFound));
                return;
            }

            //TODO start new Activity and display flights
            textViewMessage.setText(String.valueOf(flights.size()));

        } catch (Exception ex) {
            log(ex, this);
        }
    }

    //</editor-fold>
}
